package com.example.everying.framework.websocket.handler;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.everying.framework.websocket.service.WebSocketChatService;
import com.example.everying.model.entity.chat.ChatConversationEntity;
import com.example.everying.model.entity.chat.ChatMessagesEntity;
import com.example.everying.service.chat.ChatConversationService;
import com.example.everying.service.chat.ChatMessagesService;
import jakarta.websocket.Session;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class ReadMessageHandler implements MessageHandler {


    private static ChatMessagesService chatMessageService;
    private static ChatConversationService chatConversationService;

    @Autowired
    private void setService(ChatMessagesService chatMessageService,
                            ChatConversationService chatConversationService) {
        ReadMessageHandler.chatMessageService = chatMessageService;
        ReadMessageHandler.chatConversationService = chatConversationService;
    }


    /**
     * @param session 会话信息
     * @param message 消息内容
     */
    @Override
    public void handle(Session session, JSONObject message) {
        Long messageId = message.getLong("messageId"); // 消息id  改成会话id了
        String userId = WebSocketChatService.getUserId(session);
        ChatMessagesEntity entity = new ChatMessagesEntity();
        entity.setMsgStatus("1");
       boolean isSave = chatMessageService.update(entity,new LambdaQueryWrapper<ChatMessagesEntity>().eq(ChatMessagesEntity::getConversationId,messageId).ne(ChatMessagesEntity::getMsgStatus,"3"));
       // 更新条数
//
       if (!isSave) {
           log.error("保存消息失败");
           return;
       }
        String otherUserId = "";
        ChatConversationEntity chatConversationEntity = chatConversationService.getById(messageId);
       if (chatConversationEntity.getUser1Id().equals(userId)){
           chatConversationEntity.setUser1UnreadCount(0);
           otherUserId = chatConversationEntity.getUser2Id();
       }else if (chatConversationEntity.getUser2Id().equals(userId)){
           chatConversationEntity.setUser2UnreadCount(0);
           otherUserId = chatConversationEntity.getUser1Id();
       }

       chatConversationService.update(chatConversationEntity,new LambdaQueryWrapper<ChatConversationEntity>().eq(ChatConversationEntity::getId,messageId));
        // 发送消息
        JSONObject resObj = new JSONObject();
        resObj.put("type", "read");
        resObj.put("messageId", messageId);
        resObj.put("isRead",true);
        String res = resObj.toJSONString();
        WebSocketChatService.sendMessageToUserId(otherUserId, res);
    }
}
